<!-- 销售退货信息 -->
<template>
    <el-form-item>
        <el-button @click="onSubmit">保存</el-button>
    </el-form-item>
    <!-- 销售退货信息表 -->
    <h2 style="margin-left: 400px;">采购退货</h2>
    <div>
        <table class="order-table">
            <tr>
                <th colspan="8">基本信息</th>
            </tr>
            <tr>
                <td style="width:110px;">供应商名称：</td>
                <td><el-input v-model="form.vendorId" /></td>
                <td style="width:100px;">采购人员：</td>
                <td><el-input v-model="form.purchasingStaff" placeholder="请输入采购人员" style="width:100px;" /></td>
                <td style="width:100px;">退货人员：</td>
                <td><el-input v-model="form.returnsPersonnel" placeholder="请输入退货人员" style="width:120px;" disabled/></td>
                <td></td>
                <td></td>
            </tr>

            <tr>
                <td>单据主题：</td>
                <td><el-input v-model="form.documentSubject" placeholder="请输入单据主题" style="width:120px;" /></td>
                <td>单据编号：</td>
                <td><el-input v-model="form.documentNumber" placeholder="请输入单据编号" style="width:120px;" disabled/></td>
                <td>对方代表：</td>
                <td><el-input v-model="form.counterpart" style="width:120px;" /></td>
                <td style="width:100px;">我方代表：</td>
                <td><el-input v-model="form.our"/></td>
            </tr>

            <tr>
                <td>退货类别：</td>
                <td>
                    <el-select v-model="form.returnType" placeholder="请选择退货类别">
                        <el-option label="产品质量" value="产品质量" />
                        <el-option label="服务质量" value="服务质量" />
                        <el-option label="超出需求" value="超出需求" />
                        <el-option label="改变需求" value="改变需求" />
                        <el-option label="其他原因" value="其他原因" />
                    </el-select>
                </td>
                <td>退货日期：</td>
                <td><el-date-picker v-model="form.returnDate" type="date" placeholder="Pick a date" style="width:100px;" />
                </td>
                <td>关联项目：</td>
                <td>
                    <el-form-item prop="projectId">
                        <el-input placeholder="请输入" v-model="form.projectDisplay" style="width:120px;" required>
                            <template #suffix>
                                <el-button size="mini" :icon="Search" @click="openAssociatedItemDialog">
                                    <i class="el-icon-search"></i>
                                </el-button>
                            </template>
                        </el-input>
                    </el-form-item>
                </td>
                <td></td>
                <td></td>
            </tr>
        </table>
    </div>
    <p>&nbsp;</p>
    <div>
        <table class="order-table">
            <tr>
                <th colspan="8">其他信息</th>
            </tr>
            <tr>
                <td>退货方式：</td>
                <td> <el-input v-model="form.refundMethods" placeholder="请输入退货方式"/></td>
                <td>退货方式：</td>
                <td> <el-input v-model="form.returnMethods" placeholder="请输入退货方式"/></td>
                <td>收货地址：</td>
                <td colspan="3"><el-input v-model="form.returnAddress" type="textarea" /></td>
            </tr>
            <tr>
                <td>备注：</td>
                <td colspan="7">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入备注信息" />
                </td>
            </tr>
        </table>
    </div>

    <!-- 销售退货明细表 -->
    <div>
        <div class="header">
            <h2 style="margin-left: 400px;">采购退货明细</h2>
            <button @click="addNewRow">新增行</button>
        </div>
        <table>
            <thead class="order-table">
                <tr>
                    <th>序号</th>
                    <th style="width: 60px;">产品名称</th>
                    <th style="width: 60px;">产品编号</th>
                    <th style="width: 60px;">规格型号</th>
                    <th>单位</th>
                    <th>数量</th>
                    <th style="width: 60px;">单价</th>
                    <th style="width: 60px;">票据类型</th>
                    <th>税率</th>
                    <th style="width: 60px;">含税单价</th>
                    <th style="width: 60px;">未税金额</th>
                    <th>税额</th>
                    <th style="width: 60px;">总金额</th>
                    <th style="width: 60px;">是否需要出库</th>
                    <th>批号</th>
                    <th style="width: 60px;">有效日期</th>
                    <th style="width: 60px;">生产日期</th>
                    <th >到货日期</th>
                    <th>备注</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(row, index) in rows" :key="row.ordersId">
                    <td>{{ index + 1 }}</td>
                    <td><input v-model="row.productName" type="text" style="width: 60px;" disabled /></td>
                    <td><input v-model="row.productNumber" type="text" style="width: 60px;" disabled /></td>
                    <td><input v-model="row.specification" type="text" style="width: 60px;" disabled /></td>
                    <td><input v-model="row.unit" type="text" style="width: 20px;" disabled /></td>
                    <td><input v-model="row.num" type="number" style="width: 60px;" disabled /></td>
                    <td><input v-model="row.price" type="number" style="width: 60px;" disabled /></td>
                    <td><input v-model="row.billType" type="text" style="width: 60px;" disabled /></td>
                    <td><input v-model="row.rate" type="text" style="width: 60px;" disabled /></td>
                    <td><input v-model="row.includingPrice" type="number" style="width: 60px;" disabled /></td>
                    <td><input v-model="row.notTaxedMoney" type="number" style="width: 40px;" disabled /></td>
                    <td><input v-model="row.tax" type="number" style="width: 40px;" disabled /></td>
                    <td><input v-model="row.sumMoney" type="number" style="width: 60px;" disabled /></td>
                    <td><input v-model="row.outboundShipments" type="text" style="width: 60px;"  /></td>
                    <td><input v-model="row.lotNumber" type="text" style="width: 60px;" disabled /></td>
                    <td><input v-model="row.expirationDate" type="date" style="width: 60px;" disabled /></td>
                    <td><input v-model="row.manufacturingDate" type="date" style="width: 60px;" disabled /></td>
                    <td><input v-model="row.arrivalDate" type="date" style="width: 60px;" disabled /></td>
                    <td><input v-model="row.remark" type="text" style="width: 60px;" disabled /></td>
                    <td>
                        <button @click="deleteRow(row.detailsId)">删除</button>
                    </td>
                </tr>
                <tr v-if="isAdding">
                    <td>{{ rows.length + 1 }}</td>
                    <td><input v-model="newRow.productName" type="text" style="width: 60px;"
                            @click="openshoppingDialog()" />
                    </td>
                    <td><input v-model="newRow.productNumber" type="text" style="width: 60px;"  /></td>
                    <td><input v-model="newRow.specification" type="text" style="width: 60px;"  /></td>
                    <td><input v-model="newRow.unit" type="text" style="width: 20px;" /></td>
                    <td><input v-model="newRow.num" type="number" style="width: 60px;"  /></td>
                    <td><input v-model="newRow.price" type="number" style="width: 60px;" /></td>
                    <td>
                        <select v-model="newRow.billType" style="width: 60px;">
                            <option value="不开票">不开票</option>
                            <option value="增值税普通发票">增值税普通发票</option>
                            <option value="增值税普通发票">增值税普通发票</option>
                        </select>
                    </td>
                    <td><input v-model="newRow.rate" type="text" style="width: 60px;"  /></td>
                    <td><input v-model="newRow.includingPrice" type="number" style="width: 60px;"  /></td>
                    <td><input v-model="newRow.notTaxedMoney" type="number" style="width: 40px;"  /></td>
                    <td><input v-model="newRow.tax" type="number" style="width: 40px;"  /></td>
                    <td><input v-model="newRow.sumMoney" type="number" style="width: 60px;"  /></td>
                    <td>
                        <select v-model="newRow.outboundShipments" style="width: 60px;">
                            <option value="是">是</option>
                            <option value="否">否</option>
                        </select>
                    </td>
                    <td><input v-model="newRow.lotNumber" type="text" style="width: 60px;"  /></td>
                    <td><input v-model="newRow.expirationDate" type="date" style="width: 60px;"  /></td>
                    <td><input v-model="newRow.manufacturingDate" type="date" style="width: 60px;"  /></td>
                    <td><input v-model="newRow.arrivalDate" type="date" style="width: 60px;"  /></td>
                    <td><input v-model="newRow.remark" type="text" style="width: 60px;"  /></td>
                    <td>
                        <button @click="saveNewRow">保存</button>
                        <button @click="cancelAddRow">取消</button>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

    <!-- 附件部分 -->
    <div class="attachment-section">
        <h4 class="sub-title">附件管理</h4>
        <el-form ref="formRef" :model="formData" label-width="100px">
            <el-form-item label="选择文件">
                <el-upload ref="uploadRef" action="https://localhost:7269/api/FileUpload/UploadFile" :headers="headers"
                    :on-success="handleSuccess" :on-error="handleError" :show-file-list="false"
                    :http-request="customRequest">
                    <el-button type="primary">选择文件</el-button>
                </el-upload>
            </el-form-item>
        </el-form>
    </div>

    <!-- 关联项目选择对话框 -->
    <el-dialog v-model="associatedItemDialogVisible" width="500" title="关联项目选择" append-to-body>
        <el-table :data="associatedItems" highlight-current-row border size="small"
            @current-change="handleAssociatedItemChange" @row-click="handleRowClick">
            <el-table-column type="index" label="序号" />
            <el-table-column prop="projectName" label="项目名称" />
            <el-table-column prop="projectNum" label="项目编号" />
            <el-table-column prop="projectTime" label="日期" />
            <el-table-column prop="projectPeople" label="负责人" />
        </el-table>
        <template #footer>
            <el-button @click="pickAssociatedItem">确定</el-button>
        </template>
    </el-dialog>

    <!-- 关联产品名称 -->
    <el-dialog v-model="shoushopping" title="商品列表" width="800">
        <el-table :data="getshoppinglist" @row-click="handleshoppingRowClick">
            <el-table-column property="productsName" label="商品名称" width="150" />
            <el-table-column property="productsNumber" label="编号" width="200" />
            <el-table-column property="productsType" label="规格型号" />
            <el-table-column property="productsUnit" label="单位" />
        </el-table>
    </el-dialog>
</template>

<script setup>
import { watch, ref, reactive, onMounted, toRaw } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute } from 'vue-router';
import axios from 'axios';
import router from '@/router';
import { useCounterStore } from "@/stores/counter";
import { Wread, Wwrite } from "@/axios/axiosHelper";
import { Delete, Edit, Search, Share, Upload } from '@element-plus/icons-vue';

const store = useCounterStore();

const shoushopping = ref(false);

//弹出商品选择框
const openshoppingDialog = () => {
    shoushopping.value = true;
}

// 处理表格行点击事件
const handleshoppingRowClick = (row) => {
    const id = row.productsId;
    console.log('点击行的 id 为:', id);
    // 这里可以添加你需要的其他逻辑，比如跳转到详情页等
    shoushopping.value = false;
    conditionshopping(id); // 调用条件查询商品的方法
};

//存储条件查询出来的商品数据
const conditionshoppinglist = ref([
    {
        productsId: 0,
        productsName: "",
        productsNumber: "",
        productsType: "",
        productsUnit: "",
        productsNum: "",
        price: 0,
        remark: "",
        del: false
    }
]);

//条件查询商品
const conditionshopping = (id) => {
    Wread.get('/w2-read/api/Products/ShowProducts', {
        params: {
            productsId: id
        }
    })
        .then(response => {
            conditionshoppinglist.value = response.data.data;
            if (conditionshoppinglist.value.length > 0) {
                const product = conditionshoppinglist.value[0];
                newRow.value.productName = product.productsName;
                newRow.value.productNumber = product.productsNumber;
                newRow.value.specification = product.productsType;
                newRow.value.unit = product.productsUnit;
            }
        })
}

//弹出框的商品显示数据
const getshoppinglist = ref([{
    productsId: 0,
    productsName: "",
    productsNumber: "",
    productsType: "",
    productsUnit: "",
    productsNum: "",
    price: 0,
    remark: "",
    del: false
}]);

//弹出框的商品显示
const getshopping = () => {
    Wread.get('/w2-read/api/Products/GetProducts')
        .then(response => {
            getshoppinglist.value = response.data.data;
        })
}


const formRef = ref(null);
const uploadRef = ref(null);
const formData = ref({});
const message = ref('');
const messageType = ref('');

const headers = {
    'Content-Type': 'multipart/form-data'
};

const customRequest = async (options) => {
    const formData = new FormData();
    formData.append('file', options.file);
    const response = await axios.post(options.action, formData, {
        headers: headers
    });
    options.onSuccess(response.data);
    if (response.data) {
        ElMessage.success('上传成功');
        return;
    } else {
        ElMessage.success('上传失败');
        return;
    }
};

const handleError = (error) => {
    message.value = '上传失败: ' + (error.response?.data?.error || error.message);
    messageType.value = 'error';
};

const submitForm = () => {
    uploadRef.value.submit();
};

// 关联项目数据
const associatedItems = ref([{}]);

const guanlianxiangmu = () => {
    Wread.get('/w-read/api/Project/ShowProject')
        .then(res => {
            if (res.data && res.data.data) {
                associatedItems.value = res.data.data;
                console.log("查询关联项目数据", associatedItems.value);
            } else {
                console.error('接口返回数据格式不正确');
                ElMessage.error('接口返回数据格式不正确，请检查接口');
            }
        })
        .catch(error => {
            console.error('获取关联项目数据失败:', error);
            ElMessage.error('获取关联项目数据失败，请检查网络或联系管理员');
        });
};

// 生成单据编号的函数
const generateDocumentsNum = () => {
    let letters = '';
    for (let i = 0; i < 4; i++) {
        letters += String.fromCharCode(65 + Math.floor(Math.random() * 26));
    }
    let numbers = '';
    for (let i = 0; i < 10; i++) {
        numbers += Math.floor(Math.random() * 10);
    }
    return letters + numbers;
};

// 采购信息表单
const form = reactive({
    extractionId: 0,
    vendorId: '',
    purchasingStaff: '',
    returnsPersonnel: store.counterStore.userName,
    documentSubject: '',
    documentNumber: '',
    counterpart: '',
    our: '',
    ReturnType: '',
    returnDate: '',
    projectId: '',
    projectDisplay: '',
    refundMethods:'',
    returnMethods:'',
    remark: '',
});

const newProcurementId = ref(0);
// 采购退货信息方法
const onSubmit = () => {
    axios
        .post('https://localhost:7114/api/Extraction/CreateExtraction', form)
        .then((res) => {
            if (res.data.code === 100) {
                newProcurementId.value = res.data.data;
                ElMessage.success(res.data.msg);
                console.log("传递销售退货信息的Id", res.data.data);
            } else {
                ElMessage.error(res.data.msg);
            }
        })
        .catch((error) => {
            if (error.response) {
                ElMessage.error(`请求出错，状态码：${error.response.status}`);
            } else if (error.request) {
                ElMessage.error('请求已发送，但没有收到响应');
            } else {
                ElMessage.error('请求出错，请稍后重试');
            }
            console.error(error);
        });
};

// 采购明细明细数据
const rows = ref([]);
const isAdding = ref(false);
const newRow = ref({
    extractionDetailsId: '',
    productName: '',
    productNumber: '',
    specification: '',
    unit: '',
    num: '',
    price: '',
    billType: '',
    rate: '',
    includingPrice: '',
    notTaxedMoney: '',
    tax: '',
    sumMoney: '',
    outboundShipments: '',
    lotNumber: '',
    expirationDate: '',
    manufacturingDate: '',
    arrivalDate: '',
    remark: '',
    extractionId: '',
});
const route = useRoute();

onMounted(() => {
  getshopping();
  guanlianxiangmu();
  form.documentNumber = generateDocumentsNum();
});

// 新增行
const addRow = () => ({
    extractionDetailsId: '',
    productName: '',
    productNumber: '',
    specification: '',
    unit: '',
    num: '',
    price: '',
    billType: '',
    rate: '',
    includingPrice: '',
    notTaxedMoney: '',
    tax: '',
    sumMoney: '',
    outboundShipments: '',
    lotNumber: '',
    expirationDate: '',
    manufacturingDate: '',
    arrivalDate: '',
    remark: '',
    extractionId: '',
});

const addNewRow = () => {
    newRow.value = addRow();
    isAdding.value = true;
    console.log("查询新增行", newRow.value);
};

onMounted(() => {
    guanlianxiangmu();
})

// 保存新增行
const saveNewRow = () => {
    console.log(newRow.value);
    newRow.value.extractionId = newProcurementId.value;
    console.log("查询保存行", newProcurementId.value);
    axios
        .post('https://localhost:7114/api/Extraction/CreateExtractionDetails', toRaw(newRow.value))
        .then((res) => {
            if (res.data.code === 100) {
                ElMessage.success(res.data.msg);
                rows.value.push({ ...newRow.value });
                isAdding.value = false;
            } else {
                ElMessage.error(res.data.msg);
            }
        })
        .catch((error) => {
            if (error.response) {
                ElMessage.error(`请求出错，状态码：${error.response.status}`);
            } else if (error.request) {
                ElMessage.error('请求已发送，但没有收到响应');
            } else {
                ElMessage.error('请求出错，请稍后重试');
            }
            console.error(error);
        });
};

// 取消新增行
const cancelAddRow = () => {
    isAdding.value = false;
};

const Del = ref(0);

// 删除
const deleteRow = (detailsId) => {
    ElMessageBox.confirm('确认删除该行？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        Wwrite.post('w2-write/api/ItemizedReturns/DelItemizedReturns', {
            detailsId: Del.value
        })
            .then(res => {
                if (res.data.code === 100) {
                    ElMessage.success('删除成功');
                    const index = rows.value.findIndex(row => row.detailsId === detailsId);
                    if (index !== -1) {
                        rows.value.splice(index, 1);
                    }
                } else {
                    ElMessage.error(res.data.msg);
                }
            })
            .catch(error => {
                if (error.response) {
                    ElMessage.error(`请求出错，状态码：${error.response.status}`);
                } else if (error.request) {
                    ElMessage.error('请求已发送，但没有收到响应');
                } else {
                    ElMessage.error('请求出错，请稍后重试');
                }
                console.error(error);
            });
    });
};

const associatedItemDialogVisible = ref(false);
const currentAssociatedItem = ref({});

// 打开关联项目选择对话框
const openAssociatedItemDialog = () => {
    associatedItemDialogVisible.value = true;
};

// 当前选中的关联项目行
const handleAssociatedItemChange = (val) => {
    currentAssociatedItem.value = val;
};

// 行点击事件处理函数
const handleRowClick = (row) => {
    currentAssociatedItem.value = row;
};

// 选择关联项目
const pickAssociatedItem = () => {
    if (currentAssociatedItem.value) {
        form.projectId = currentAssociatedItem.value.projectId;
        form.projectDisplay = currentAssociatedItem.value.projectName; // 更新显示的值
        associatedItemDialogVisible.value = false;
    }
};

const batchUpload = () => {
    ElMessageBox.confirm('确认上传选中文件？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        ElMessage.info('批量上传功能待完善具体逻辑');
    });
};
</script>

<style scoped>
.order-table {
    border-collapse: collapse;
    width: 100%;
}

.order-table th,
.order-table td {
    border: 1px solid #ccc;
    padding: 8px;
    text-align: left;
}

.order-table th {
    background-color: #f2f2f2;
}
</style>

<style scoped>
#app {
    padding: 20px;
}
</style>